package com.eliza.library.device.bluethooth

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import com.eliza.library.permission.PermissionUtils


class BluetoothTools(val context: Context) {
    val bluetoothAdapter: BluetoothAdapter

    init {
        val systemService: BluetoothManager =
            context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = systemService.adapter
        if (bluetoothAdapter == null) {

        }
    }


    fun isSupport() = bluetoothAdapter != null

    fun blueToothStatue() = bluetoothAdapter.isEnabled ?: false

    // 已經配對
    fun getBondedDevices(): Set<BluetoothDevice> {
        if (ActivityCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_CONNECT
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return bluetoothAdapter.bondedDevices
        }

        return emptySet<BluetoothDevice>()
    }

    fun setDiscoverable(open: Boolean, requestCode: Int): Boolean {
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.BLUETOOTH_SCAN
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            PermissionUtils.requestPermissions(
                context as Activity,
                requestCode,
                *if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    arrayOf(
                        Manifest.permission.BLUETOOTH_SCAN
                    )
                } else {
                    arrayOf(Manifest.permission.BLUETOOTH_ADMIN)
                }
            )
        }
        if (open) {
            bluetoothAdapter.startDiscovery()
        } else {
            bluetoothAdapter.cancelDiscovery()
        }
        return bluetoothAdapter.isDiscovering
    }

    fun turnState(open: Boolean, activity: Activity, requestCode: Int): Boolean {
        if (ActivityCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            PermissionUtils.requestPermissions(
                activity,
                1,
                Manifest.permission.BLUETOOTH,
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    Manifest.permission.BLUETOOTH_CONNECT
                } else {
                    Manifest.permission.BLUETOOTH_ADMIN
                }
            )
        }
        if (open) {
            if (!bluetoothAdapter.isEnabled) {
                activity.startActivityForResult(
                    Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), requestCode
                )
            }
        } else {
            if (bluetoothAdapter.isEnabled) {
                bluetoothAdapter.disable()
            }
        }
        return bluetoothAdapter.isEnabled
    }

    fun setScanner(open: Boolean, callback: ScanCallback): Boolean {
        if (ActivityCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_SCAN
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            PermissionUtils.requestPermissions(
                context as Activity, 1001,
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    Manifest.permission.BLUETOOTH_SCAN
                } else {
                    Manifest.permission.BLUETOOTH
                }
            )
        }
        return if (open) {
            bluetoothAdapter.bluetoothLeScanner.startScan(callback)
            open
        } else {
            bluetoothAdapter.bluetoothLeScanner.stopScan(callback)
            open
        }
    }

    //您的应用必须为 ACTION_FOUND intent 注册一个 BroadcastReceiver

    fun canBeFound(activity: Activity, requestCode: Int, second: Int = 300) {
        val discoverableIntent: Intent =
            Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
                putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, second)
            }
        activity.startActivityForResult(discoverableIntent, requestCode)
    }

    fun isDiscovering(): Boolean {
        if (ActivityCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_SCAN
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return false
        }
        return bluetoothAdapter.isDiscovering
    }

    fun isEnabled(): Boolean {
        return bluetoothAdapter.isEnabled
    }


}

//必须为 ACTION_FOUND intent 注册一个 BroadcastReceiver
//系统会为每个设备广播此 intent。该 intent 包含 extra 字段 EXTRA_DEVICE 和 EXTRA_CLASS，而这两个字段分别包含 BluetoothDevice 和 BluetoothClass。
object BluetoothTool {
    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice? =
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                            intent.getParcelableExtra(
                                BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java
                            )
                        } else {
                            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                        }
                    Log.d("BluetoothTool", "BluetoothTool Receiver")

                    if (ActivityCompat.checkSelfPermission(
                            context, Manifest.permission.BLUETOOTH_CONNECT
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        return
                    }
                    device?.let {
                        Log.d("BluetoothTool", it.name)
                        Log.d("BluetoothTool", it.address)
                    }
                }
            }
        }
    }

}

//SCAN_MODE_CONNECTABLE_DISCOVERABLE
//设备处于可检测到模式。
//SCAN_MODE_CONNECTABLE
//设备未处于可检测到模式，但仍然可以接收连接。
//SCAN_MODE_NONE
//设备未处于可检测到模式，因此无法接收连接。
//如果您是要发起与远程设备的连接，则无需启用设备可检测性。仅当您希望应用托管用于接受传入连接的服务器套接字时，才有必要启用可检测性，因为远程设备必须能够发现其他设备，然后才能发起与这些设备的连接。


/*
作为服务器连接
    当您想要连接两台设备时，其中一台设备必须保持打开的 BluetoothServerSocket 来充当服务器。
    服务器套接字的用途是监听传入的连接请求，并在接受请求后提供已连接的 BluetoothSocket。
    从 BluetoothServerSocket 获取 BluetoothSocket 后，您可以并且应该舍弃 BluetoothServerSocket，
    除非您希望设备接受更多连接。
*/

